var crypto = require('crypto');
var AliConfig = {
	partner: "2088221878061388",
	seller: "13401029991@139.com",
	rsa_private_key_pem: './framework/rsa_pem/rsa_private_key.pem',
	rsa_public_key_pem: './framework/rsa_pem/rsa_ali_public_key.pem'
}
var AliPayHelper = {

	partner: AliConfig.partner,

	order_sign: function(orderinfo) {
		var fs = require('fs');
		var key = fs.readFileSync(AliConfig.rsa_private_key_pem);
		var signer = crypto.createSign("RSA-SHA1");
		signer.update(orderinfo);
		return signer.sign(key, "base64");
	},

	getSuccessStr: function() {
		return "success";
	},

	getFailStr: function() {
		return "fail";
	},

	result_verify: function(body, callback) {
		var body_sort = Object.keys(body).sort();

		var sort_result = {};
		for (var i = 0; i < body_sort.length; i++) {
			sort_result[body_sort[i]] = body[body_sort[i]]
		}

		delete sort_result.sign;
		delete sort_result.sign_type;

		var sign_str = "";
		for (var item in sort_result) {
			if (sign_str != "") {
				sign_str += "&"
			}
			sign_str += item;
			sign_str += "=";
			sign_str += body[item];
		}

		var fs = require('fs');
		var key = fs.readFileSync(AliConfig.rsa_public_key_pem);
		var verifier = crypto.createVerify("RSA-SHA1");
		verifier.update(sign_str);


		var result = verifier.verify(key, body.sign, "base64");

		if (result == true) {
			var request = require('request');
			var url = "https://mapi.alipay.com/gateway.do?service=notify_verify&partner=" + AliPayHelper.partner + "&notify_id=" + body.notify_id;
			console.log(url);
			request.get(url, function(error, response, notify_body) {
				console.log(error);
				if (!error && response.statusCode == 200) {
					if (notify_body == "true") {
						if (body.seller_id == AliPayHelper.partner) {
							callback(0);
							return;
						}
					}

					callback(1);
				}
			});
		} else {
			callback(1);
		}
	}

}

module.exports = AliPayHelper;